package com.qf.shopsso.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.qf.common.result.ResultEntity;
import com.qf.common.constant.RabbitMqConstants;
import com.qf.common.utils.JwtUtils;
import com.qf.common.utils.PasswordEncoding;
import com.qf.entity.Email;
import com.qf.entity.User;
import com.qf.feign.UserFeignService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sso")
public class SsoController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserFeignService userFeignService;

    @RequestMapping("/register")
    public ResultEntity reg(User user, String code) {
        //从redis中获取用户注册的验证码，和注册页面输入传过来的对比
        String redisCode = redisTemplate.opsForValue().get(RabbitMqConstants.SSO_REGISTER_CODE_KEY + user.getEmail());
        System.out.println("redis的验证码:" + RabbitMqConstants.SSO_REGISTER_CODE_KEY + user.getEmail());
        if (!code.equals(redisCode)) {
            return ResultEntity.error("验证码错误或已经过期");
        }
        //对密码进行加密,先取值，进行加密，在赋值
        user.setPassword(PasswordEncoding.hashPw(user.getPassword()));
        //加入数据库
             return userFeignService.addUser(user);

    }

    //required = false,有就传，没有就不传，=true时，不传会报错
    @RequestMapping("/getUserByUsernameToken")
    public ResultEntity getUserByUsernameToken(@RequestHeader(name = RabbitMqConstants.LOGIN_TOKEN, required = false) String token) {
        //判断是否空
        if (!StringUtils.isEmpty(token)) {
            //检验token
            DecodedJWT decodedJWT = JwtUtils.checkToken(token);
            //在token里获得user信息
            String username = JwtUtils.getWithClaim("username", decodedJWT);
            String email = JwtUtils.getWithClaim("email", decodedJWT);
            User user = new User();
            user.setUsername(username);
            user.setEmail(email);

            return ResultEntity.success(user);
        } else {
            return ResultEntity.error("token是空的");
        }

    }

    @RequestMapping("/Login")
    public ResultEntity login(String username, String password) {
        System.out.println("username = [" + username + "], password = [" + password + "]");
        //判断用户是否存在
        User user = userFeignService.getUserByUsername(username);
        if (user == null) {
            return ResultEntity.error("用户名或者密码错误了u");
        }
        //确认密码,前一个参数是传过来的psw，后一个是数据库查询的密码，两者对比
        boolean result = PasswordEncoding.checkPw(password, user.getPassword());
        if (!result) {
            return ResultEntity.error("用户名或者密码错误了p");

        }
        //登录成功后，生成token,用map把信息存进去
        Map<String, String> map = new HashMap<>();
        map.put("username", user.getUsername());
        map.put("password", user.getPassword());
        map.put("id", user.getId().toString());
        //生成有效期为七天的token，再把这个token返回回去
        String token = JwtUtils.createToken(map, 60 * 60 * 24 * 7);
        return ResultEntity.success(token);
    }

    @RequestMapping("/validateUsername")
    public Map<String, Object> validateUsername(String param) {
        Map<String, Object> map = new HashMap<>();
        User username = userFeignService.getUserByUsername(param);
        //如果查到这个名字，判断不为空，说明已经被注册了
        if (username != null) {
            map.put("status", "n");
            map.put("info", "用户名被注册");
        } else {
            map.put("status", "y");
            map.put("info", "用户名可用");
        }
        return map;
    }

    @RequestMapping("/sendEmail")
    public void sendEmail(String email) {
        //生成验证码
        String code = RandomStringUtils.random(4, false, true);
        Email emailEntity = new Email();
        emailEntity.setTitle("2009-final-商城项目");
        emailEntity.setContent("验证码为:" + code);
        //前端输入的邮箱
        emailEntity.setToUser(email);

        //发送消息到mq交换机
        rabbitTemplate.convertAndSend(RabbitMqConstants.EMAIL_EXCHANGE, null, emailEntity);
        //要在email前加上对应模块的key,验证码,存入redis
        redisTemplate.opsForValue().set(RabbitMqConstants.SSO_REGISTER_CODE_KEY + email, code, 30, TimeUnit.SECONDS);
    }
}
